package com.xu.cloud.common.pojo;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.xu.cloud.common.exception.ErrorCodeEnum;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 统一返回实体类
 *
 * @author xuguan
 * @since 2023/2/2
 */
public class Result<T> implements Serializable {
    private static final long serialVersionUID = -2679174778544913577L;

    private boolean success;
    private String code;
    private String msg;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private final LocalDateTime respTime = LocalDateTime.now();
    private T data;

    public Result() {
    }

    public Result(String code, String msg, T data) {
        this.success = ErrorCodeEnum.OK.getCode().equals(code);
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public LocalDateTime getRespTime() {
        return respTime;
    }

    public T getData() {
        return data;
    }

    public static <T> Result<T> ok(T data) {
        return new Result<>(ErrorCodeEnum.OK.getCode(), ErrorCodeEnum.OK.getMessage(), data);
    }

    public static <T> Result<T> fail(String code, String msg, T data) {
        return new Result<>(code, msg, data);
    }

    @Override
    public String toString() {
        return "Result{" +
                "success=" + success +
                ", code='" + code + '\'' +
                ", msg='" + msg + '\'' +
                ", respTime=" + respTime +
                ", data=" + data +
                '}';
    }
}
